package cn.zlg.www.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;


import com.sany.canwifi.R;

import cn.zlg.www.main.ItemData;
import cn.zlg.www.main.MainActivity;

public class SendFragment extends Fragment {
	private View mView;
	private boolean mIsNormalSend = true;
	private boolean mIsExtend = false;
	private boolean mIsRemote = false;
	public static final int NUMCOUNT = 10;
	private MainActivity mainActivity;
	private SendRunnable mSendRunnable;
	private RelativeLayout mSendTypeLayout, mFrmTypeLayout, mFormatLayout,
			mSendLayout;
	private TextView mSendTextView, mSendTypeTextView, mFrmTypeTextView,
			mFrmFormatTextView;
	private LayoutOnClickListener mLayoutOnClickListener;
	private boolean mSending = false;
	public static final int SENDBUTTONFLAG = 0;
	private MsgHandler mMsgHandler;
	private boolean mPaused;

	public SendFragment() {
		super();
		mMsgHandler = new MsgHandler();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (null == mainActivity) {
			mainActivity = (MainActivity) getActivity();
		}
		mView = inflater.inflate(R.layout.sending, null);

		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mSendTextView = (TextView) mView.findViewById(R.id.textViewSendFrm);
		mSendTextView.setText(mSending ? "停止" : "发送");
		mSendTypeTextView = (TextView) mView
				.findViewById(R.id.textViewSendType2);
		mSendTypeTextView.setText(mIsNormalSend ? "正常发送" : "自发自收");
		mFrmTypeTextView = (TextView) mView.findViewById(R.id.textViewFrmType2);
		mFrmTypeTextView.setText(mIsExtend ? "扩展帧" : "标准帧");
		mFrmFormatTextView = (TextView) mView
				.findViewById(R.id.textViewSendFormat2);
		mFrmFormatTextView.setText(mIsRemote ? "远程帧" : "数据帧");
		mLayoutOnClickListener = new LayoutOnClickListener();
		mSendTypeLayout = (RelativeLayout) mView
				.findViewById(R.id.sendTypeLayout);
		mSendTypeLayout.setOnClickListener(mLayoutOnClickListener);
		mFrmTypeLayout = (RelativeLayout) mView
				.findViewById(R.id.frmTypeLayout);
		mFrmTypeLayout.setOnClickListener(mLayoutOnClickListener);
		mFormatLayout = (RelativeLayout) mView
				.findViewById(R.id.frmFormatLayout);
		mFormatLayout.setOnClickListener(mLayoutOnClickListener);
		mSendLayout = (RelativeLayout) mView.findViewById(R.id.sendFrmLayout);
		mSendLayout.setOnClickListener(mLayoutOnClickListener);
	}

	private void sendFrms(ItemData itemData, int nCount, boolean bIncred,
                          int nInterval) {
		if (itemData.nID >= 0x800 && !itemData.bExtend) {
			itemData.nID = 0;
		}
		for (long i = 0; i < nCount; i++) {
			ItemData item = new ItemData(itemData);
			if (bIncred) {
				item.nID += i;
			}
			if (itemData.nID >= 0x800 && !itemData.bExtend) {
				itemData.nID -= 0x800;
			}
			try {
				item.nTime = System.currentTimeMillis();
				mainActivity.doCommand(MainActivity.TYPE_SEND_FRM, item);
				Thread.sleep(nInterval);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void sendFrm() {
		String strID = ((EditText) mView.findViewById(R.id.editTextID))
				.getText().toString();
		if (strID.equals("")) {
			Toast toast = Toast.makeText(mainActivity, "ID为空",
					Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
			return;
		}
		String strData = ((EditText) mView.findViewById(R.id.editTextData))
				.getText().toString();
		if (strData.equals("")) {
			Toast toast = Toast.makeText(mainActivity, "数据为空",
					Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
			return;
		}
		ItemData itemData = new ItemData();
		int nLen = splitString(itemData.datas, strData);
		itemData.bExtend = mIsExtend;
		itemData.bRecv = false;
		itemData.bRemote = mIsRemote;
		itemData.nSendType = (byte) (mIsNormalSend ? 0 : 1);
		itemData.nDataLen = (byte) nLen;
		itemData.nID = Long.parseLong(strID, 16);
		String strNum = ((EditText) mView.findViewById(R.id.textviewNum))
				.getText().toString();
		int num = 1;
		if (!strNum.equals("")) {
			num = Integer.parseInt(strNum);
		}
		int nInterval = 0;
		String strIntervalString = ((EditText) mView
				.findViewById(R.id.EditTextInterval)).getText().toString();
		if (!strIntervalString.equals("")) {
			nInterval = Integer.parseInt(strIntervalString);
		}
		boolean bIncred = ((Switch) mView.findViewById(R.id.switchIncred))
				.isChecked();
		if (num < NUMCOUNT) {
			sendFrms(itemData, num, bIncred, nInterval);
			setSendBtnFlag(false);
		} else {
			mSendRunnable = new SendRunnable(itemData, num, bIncred, nInterval);
			Thread thread = new Thread(mSendRunnable);
			thread.start();
		}
	}

	private int splitString(short[] datas, String strData) {
		String[] strings = strData.split(" ");
		for (int i = 0; i < strings.length; i++) {
			if (!strings[i].equals("")) {
				datas[i] = Short.parseShort(strings[i], 16);
			}
		}
		return strings.length;
	}

	public void setSendBtnFlag(boolean bSend) {
		mSending = bSend;
		mSendTextView.setText(mSending ? "停止" : "发送");
	}

	private class SendRunnable implements Runnable {

		private ItemData mItemData;
		private long mCount;
		private boolean mBincred;
		private boolean mRun;
		private int mInterval;

		public SendRunnable(ItemData itemData, long nCount, boolean bIncred,
                            int nInterval) {
			// TODO Auto-generated constructor stub
			mItemData = itemData;
			if (mItemData.nID >= 0x7FF && !mItemData.bExtend) {
				mItemData.nID = 0;
			}
			mCount = nCount;
			mBincred = bIncred;
			mRun = true;
			mInterval = nInterval;
		}

		public void stop() {
			mRun = false;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			for (long i = 0, j = 0; i < mCount; ++i, ++j) {
				if (!mRun) {
					break;
				}
				ItemData itemData = new ItemData(mItemData);
				if (mBincred) {
					itemData.nID += j;
				}
				if (itemData.nID >= 0x7FF && !itemData.bExtend) {
					mItemData.nID = 0;
					j = -1;
				}
				try {
					itemData.nTime = System.currentTimeMillis();
					mainActivity
							.doCommand(MainActivity.TYPE_SEND_FRM, itemData);
					Thread.sleep(mInterval);

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			Message msg = new Message();
			msg.what = SENDBUTTONFLAG;
			msg.arg1 = 0;
			mMsgHandler.sendMessage(msg);
		}
	}

	@SuppressLint("HandlerLeak")
	private class MsgHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
				case SENDBUTTONFLAG:
					int flag = msg.arg1;
					setSendBtnFlag(1 == flag);
					break;
				default:
					break;
			}
		}
	}

	public void setSendStatus(boolean bPaused) {
		mPaused = bPaused;
		if (mPaused && mSendRunnable != null) {
			mSendRunnable.stop();
			setSendBtnFlag(false);
		}
	}

	private class LayoutOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
				case R.id.sendTypeLayout:
					mIsNormalSend = !mIsNormalSend;
					mSendTypeTextView.setText(mIsNormalSend ? "正常发送" : "自发自收");
					break;
				case R.id.frmTypeLayout:
					mIsExtend = !mIsExtend;
					mFrmTypeTextView.setText(mIsExtend ? "扩展帧" : "标准帧");
					break;
				case R.id.frmFormatLayout:
					mIsRemote = !mIsRemote;
					mFrmFormatTextView.setText(mIsRemote ? "远程帧" : "数据帧");
					break;
				case R.id.sendFrmLayout:
					if (mPaused) {
						Toast toast = Toast.makeText(mainActivity, "应用已暂停，不能发送",
								Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						return;
					}
					if (!mSending) {
						setSendBtnFlag(true);
						sendFrm();
					} else {
						mSendRunnable.stop();
						setSendBtnFlag(false);
					}
					break;
				default:
					break;
			}
		}
	}
}
